package allTests;

import abbot.WaitTimedOutException;
import abbot.finder.matchers.ClassMatcher;
import abbot.finder.matchers.NameMatcher;
import abbot.tester.ActionFailedException;
import abbot.util.AWTFixtureHelper;
import abbot.util.Condition;
import com.supermap.data.Datasource;
import com.supermap.data.Point2D;
import com.supermap.desktop.controls.ui.FormBaseChild;
import com.supermap.desktop.controls.ui.trees.WorkspaceTree;
import com.supermap.desktop.core.Application;
import com.supermap.desktop.core.Interface.IForm;
import com.supermap.desktop.core.utilties.SystemPropertyUtilities;
import operation.*;
import org.junit.*;
import org.junit.rules.ErrorCollector;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import robotCross.CrossRobot;
import robotCross.TipMatcher;
import socketEnv.CrossProperties;
import socketEnv.DataUtil;
import util.Info;
import util.Platform;
import util.ScreenImage;
import util.ZipUtil;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.net.URL;

import static operation.Operation.robot;
import static operation.RibbonOperation.RIBBONOPERATION;


/**
 * Created by hanyz on 2016/8/30.
 */
@RunWith(BlockJUnit4ClassRunner.class)
public class TestMap {
	String picturePath = DataUtil.resultPicturePath + "TestMap\\";
	@Rule
	public final ErrorCollector errorCollector = new ErrorCollector();
	CompareOperation compareOperation = CompareOperation.getInstance(errorCollector);
	@Before
	public void runBeforeTestMethod() {
		Info.out("@Before - runBeforeTestMethod");
		Operation.helper = new AWTFixtureHelper();
		Operation.robot = Operation.helper.getRobot();
		DialogOperation.closeAllDialog();
	}

	@After
	public void runAfterTestMethod() throws Exception {
		Info.out("@After - runAfterTestMethod");
		DialogOperation.closeAllDialog();
		WorkspaceTreeOperation.closeWorkspace();
	}

	@Test
	public void testUniqueTheme() throws Exception {
		String dataSourceName = "打开文件型数据源...";
		new WorkspaceTreeOperation().selectTheDatasouceNodeMenu(dataSourceName);
		new JFileChooserOperation().chooseFile(DataUtil.testDataPath + "SampleData/City/Jingjin.udb");
		robot.delay(2000);
		new WorkspaceTreeOperation().selectDatasetNodeMenu("Jingjin", "BaseMap_R", "添加到新地图");
		robot.delay(3000);
		RIBBONOPERATION.clickButton("专题图", "专题图");
		robot.delay(1000);
		MapOperation mapOperation = new MapOperation();
		mapOperation.clickThemeItem("单值专题图", "默认");
		DockbarOperation dockbarOperation = new DockbarOperation("专题图");
		robot.delay(1000);
		dockbarOperation.clickTab("属性");
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("ThemeUniqueContainer_comboBoxExpression"), "POP_1999");
		robot.delay(1000);
		dockbarOperation.clickColorScheme("ThemeUniqueContainer_comboboxColor", "CA_Red Rose");
		Component component = dockbarOperation.searchComponent(new NameMatcher("ThemeUniqueContainer_tableUniqueInfo"));
		Component component1 = dockbarOperation.searchComponent(new NameMatcher("ThemeUniqueContainer_buttonDelete"));
		TableOperation tableOperation = new TableOperation((JTable) component);
		tableOperation.selectRows(3, 6);
		dockbarOperation.clickComponent(component1);
		robot.delay(1000);
		mapOperation.clickMapMenuItem("漫游");
		Point2D[] point2Ds = {new Point2D(115.9644333, 40.01031388), new Point2D(116.16841944444445, 39.99671388888889)};
		mapOperation.dragMouse(point2Ds[0]);
		mapOperation.dropMouse(point2Ds[1]);
		ScreenImage.printDesktopImage(picturePath+"UniqueTheme.png");
		robot.delay(2000);
	}

	@Test
	public void testRangeTheme() throws Exception {
		String dataSourceName = "打开文件型数据源...";
		new WorkspaceTreeOperation().selectTheDatasouceNodeMenu(dataSourceName);
		new JFileChooserOperation().chooseFile(DataUtil.testDataPath + "SampleData/China/China.udb");
		robot.delay(2000);
		new WorkspaceTreeOperation().selectDatasetNodeMenu("China", "MainRiver_R|China_Province_pg", "添加到新地图");
		robot.delay(5000);
		new LayerTreeOperation().selectLayerNodeMenu("MainRiver_R@China", "可显示");
		new LayerTreeOperation().selectLayerNodeMenu("China_Province_pg@China", "制作专题图...");
		robot.delay(3000);
		MapOperation mapOperation = new MapOperation();
		mapOperation.clickThemeItem("分段专题图", "默认");
		DockbarOperation dockbarOperation = new DockbarOperation("专题图");
		robot.delay(1000);
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("ThemeRangeContainer_comboBoxExpression"), "Popu_2010");
		robot.delay(1000);
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("ThemeRangeContainer_comboBoxRangeMethod"), "平方根分段");
		robot.delay(1000);
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("ThemeRangeContainer_comboBoxRangeCount"), "8");
		robot.delay(1000);
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("ThemeRangeContainer_comboBoxRangePrecision"), "0.01");
		robot.delay(1000);
		dockbarOperation.clickColorScheme("ThemeRangeContainer_comboBoxColorStyle", "CD_Cyans");
		dockbarOperation.clickComponent(new NameMatcher("ThemeRangeContainer_buttonContinuousMapLocation"));
		Component component = dockbarOperation.searchComponent(new NameMatcher("ThemeRangeContainer_tableRangeInfo"));
		TableOperation tableOperation = new TableOperation((JTable) component);
		tableOperation.clickTableCell(4, 1);
		robot.delay(1000);
		mapOperation.clickMapMenuItem("全幅显示");
		robot.delay(1000);
		ScreenImage.printComponentImage((JComponent) mapOperation.container, picturePath+"testRangeTheme.png");
	}

	@Test
	public void testLabelUniformTheme() throws Exception {
		String dataSourceName = "打开文件型数据源...";
		new WorkspaceTreeOperation().selectTheDatasouceNodeMenu(dataSourceName);
		new JFileChooserOperation().chooseFile(DataUtil.testDataPath + "SampleData/China/China.udb");
		robot.delay(2000);
		new WorkspaceTreeOperation().selectDatasetNodeMenu("China", "China_Province_pg", "添加到新地图");
		robot.delay(5000);
		new LayerTreeOperation().selectLayerNodeMenu("China_Province_pg@China", "制作专题图...");
		robot.delay(3000);
		MapOperation mapOperation = new MapOperation();
		mapOperation.clickThemeItem("标签专题图", "统一风格");
		DockbarOperation dockbarOperation = new DockbarOperation("专题图");
		robot.delay(1000);
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("ThemeLabelPropertyPanel_comboBoxExpression"), "省级行政单位");
		robot.delay(1000);
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("ThemeLabelPropertyPanel_comboBoxBGShape"), "矩形");
		robot.delay(500);
		dockbarOperation.clickComponent(new NameMatcher("ThemeLabelPropertyPanel_checkBoxFlowVisual"));
		robot.delay(500);
		dockbarOperation.clickTab("风格");
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("TextBasicPanel_comboBoxFontName"), "幼圆");
		robot.delay(500);
		dockbarOperation.editComboBox(new NameMatcher("TextBasicPanel_comboBoxFontSize"), "14");
		dockbarOperation.clickComponent(new NameMatcher("TextBasicPanel_checkBoxItalic"));
		robot.delay(500);
		dockbarOperation.clickTab("高级");
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("ThemeLabelAdvancePanel_comboBoxOverLength"), "换行显示");
		dockbarOperation.setSpinnerValue(new NameMatcher("ThemeLabelAdvancePanel_spinnerFontCount"), "4");
		dockbarOperation.clickTab("风格");
		ScreenImage.printDesktopImage(picturePath+"testLabelUniformTheme.png");
	}

	@Test
	public void testStatisticTheme() throws Exception {
		String dataSourceName = "打开文件型数据源...";
		new WorkspaceTreeOperation().selectTheDatasouceNodeMenu(dataSourceName);
		new JFileChooserOperation().chooseFile(DataUtil.testDataPath + "SampleData/China/China.udb");
		robot.delay(2000);
		new WorkspaceTreeOperation().selectDatasetNodeMenu("China", "China_Province_pg", "添加到新地图");
		robot.delay(5000);
		new LayerTreeOperation().selectLayerNodeMenu("China_Province_pg@China", "制作专题图...");
		robot.delay(3000);
		MapOperation mapOperation = new MapOperation();
		mapOperation.clickThemeItem("统计专题图", "默认");
		DockbarOperation dockbarOperation = new DockbarOperation("专题图");
		robot.delay(1000);
		Component component = dockbarOperation.searchComponent(new NameMatcher("ThemeGraphContainer_tableGraphInfo"));
		TableOperation tableOperation = new TableOperation((JTable) component);
		tableOperation.clickTableCell(0, 0);
		dockbarOperation.clickComponent(new NameMatcher("ThemeGraphContainer_buttonDelete"));
		dockbarOperation.clickComponent(new NameMatcher("ThemeGraphContainer_buttonAdd"));
		robot.delay(2000);
		String[] itemNames = {"Popu_2010", "Popu_2011", "Popu_2012", "Popu_2002"};
		mapOperation.clickAddDialogItem(itemNames);
		dockbarOperation.clickColorScheme("ThemeGraphContainer_comboBoxColor", "DA_Ragular");
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("ThemeGraphContainer_comboBoxGraphType"), "三维柱状图");
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("ThemeGraphContainer_comboBoxMethod"), "平方根");
		robot.delay(1000);
		dockbarOperation.clickTab("高级");
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("ThemeGraphContainer_comboBoxAxisModel"), "全部显示");
		dockbarOperation.editTextField(new NameMatcher("WaringTextField_textField"), "2");
		robot.delay(1000);
		mapOperation.clickMapMenuItem("放大");
		new CrossRobot().clickLeftMouse();
		new CrossRobot().clickLeftMouse();
		robot.delay(1000);
		ScreenImage.printDesktopImage(picturePath+"testStatisticTheme.png");
	}

	@Test
	//用烟台数据做刺点配准
	public void testTransformation() throws Exception {
		String testWorkspacePath = DataUtil.testDataPath + "Map/Transformation/yantai.smwu";
		String expDsPath = DataUtil.resultPath_exp + "Map/Transformation/testTransformation.udb";
		String resultDsPath = DataUtil.resultPath_actual + "Map/Transformation/testTransformation.udb";

		//打开工作空间
		new CommonOperation().openSMWU(testWorkspacePath);
		//新建数据源
		new CommonOperation().createUDB(resultDsPath);
		//新建配准
		RIBBONOPERATION.clickDropDownButton("开始", "新建配准", "新建配准");
		//选择地图作为配准数据
		DialogOperation dialogOperation = new DialogOperation();
		dialogOperation.clickComponent(new NameMatcher("JPanelChooseOriginal_buttonAdd"));
		DialogOperation selectOperation = new DialogOperation("选择");
		WorkspaceTree workspaceTree = (WorkspaceTree) selectOperation.searchComponent(new ClassMatcher(WorkspaceTree.class));
		new WorkspaceTreeOperation(workspaceTree).selectTheMapNode();
		Component selectDatasetTable = selectOperation.searchComponent(new ClassMatcher(JTable.class));
		new TableOperation((JTable) selectDatasetTable).selectRow(1);
		selectOperation.clickComponent(new TipMatcher("确定"));
		dialogOperation.clickComponent(new NameMatcher("JDialogNewTransformation_buttonNext"));
		//选择地图作为参考数据
		dialogOperation.clickComponent(new NameMatcher("JPanelChooseRefer_buttonAdd"));
		selectOperation = new DialogOperation("选择");
		workspaceTree = (WorkspaceTree) selectOperation.searchComponent(new ClassMatcher(WorkspaceTree.class));
		new WorkspaceTreeOperation(workspaceTree).selectTheMapNode();
		selectDatasetTable = selectOperation.searchComponent(new ClassMatcher(JTable.class));
		new TableOperation((JTable) selectDatasetTable).selectRow(0);
		selectOperation.clickComponent(new TipMatcher("确定"));
		dialogOperation.clickComponent(new NameMatcher("JDialogNewTransformation_buttonNext"));
		//下一步，完成
		dialogOperation.clickComponent(new NameMatcher("JDialogNewTransformation_buttonNext"));
		new CommonOperation().waitForWindowDispose(dialogOperation.getContainer(), 10000);
		//设置配准地图图层属性，不拉伸
		robot.delay(2000);
		new LayerTreeOperation().selectLayerNodeMenu("烟台_toAdjust@Transformation_yantai", "图层属性");
		DockbarOperation dockbarOperation = new DockbarOperation("图层属性");
		dockbarOperation.setComboBoxSelectedItem(new NameMatcher("LayerStretchOptionPropertyControl_comboBoxStretchType"),"无拉伸");
		//刺点
		IForm activeForm = Application.getActiveApplication().getActiveForm();
		FormBaseChild form = null;
		if (activeForm instanceof FormBaseChild) {
			form = (FormBaseChild) activeForm;
		}
		JSplitPane splitPaneMapControls = (JSplitPane) new Operation(form).searchComponent(new NameMatcher("FormTransformation_splitPaneMapControls"));
		Component targetMapControl = splitPaneMapControls.getLeftComponent();
		Component referenceMapControl = splitPaneMapControls.getRightComponent();
		Point2D[] point2Ds_target = new Point2D[]{
				new Point2D(723.81680, 929.3664269),
				new Point2D(23.500253, 442.373508),
				new Point2D(1242.9720286, 167.7360663),
				new Point2D(1412.720027, 485.757628)};
		Point2D[] point2Ds_reference = new Point2D[]{
				new Point2D(1355236.830275, 4159934.523836),
				new Point2D(1262383.735023, 4067992.401000),
				new Point2D(1449842.533909, 4050718.99746),
				new Point2D(1468305.83560, 4104127.40017)};
		MapOperation targetMapOperation = new MapOperation((Container) targetMapControl);
		MapOperation referenceMapOperation = new MapOperation((Container) referenceMapControl);
		targetMapOperation.clickMapMenuItem("全幅显示");
		referenceMapOperation.clickMapMenuItem("全幅显示");
		RIBBONOPERATION.clickButton("配准", "刺点");
		for (int i = 0; i < point2Ds_target.length; i++) {
			targetMapOperation.clickPoint(point2Ds_target[i]);
			referenceMapOperation.clickPoint(point2Ds_reference[i]);
		}
		//计算误差
		RIBBONOPERATION.clickButton("配准", "计算误差");
		//执行配准
		RIBBONOPERATION.clickButton("配准", "配准");
		DialogOperation dialogOperation1 = new DialogOperation();
		dialogOperation1.clickComponent(new NameMatcher("JDialogTransformation_buttonOk"));
		new CommonOperation().waitForProgressDispose(6000);

		//结果数据集对比
		Datasource resultDatasource = CommonOperation.getDatasource("testTransformation");
		Datasource expDatasource = CommonOperation.openDatasource(expDsPath);
		boolean compareResult = compareOperation.compareDataset(expDatasource, resultDatasource);
		Assert.assertTrue(compareResult);
	}

	@Test@Platform
	//发布iserver服务
	public void testIServer() throws Exception {
		String workspacePath = DataUtil.testDataPath + "SampleData/China/China.smwu";
		String iserverPath_remote = "Map/IServer/";
		String iserverPath_local = DataUtil.localDataPath + "Map/IServer/";
		String iserverPackageName = "supermap_iserver_win64";
		String startBatPath = iserverPath_local + iserverPackageName + "/bin/startup.bat";
		String shutdownBatPath = iserverPath_local + iserverPackageName + "/bin/shutdown.bat";

		if(SystemPropertyUtilities.isLinux()){
			iserverPackageName = "supermap_iserver_linux64";
			startBatPath = iserverPath_local + iserverPackageName + "/bin/startup.sh";
			shutdownBatPath = iserverPath_local + iserverPackageName + "/bin/shutdown.sh";
		}
		//复制iserver包到本地
		Info.out("复制iserver包到本地...");
		String iserverZip_remote = iserverPath_remote + iserverPackageName + ".zip";
		DataUtil.copyData(iserverZip_remote);
		//解压iserver包
		String iserverZip_local = iserverPath_local + iserverPackageName + ".zip";
		Info.out("解压iserver包...");
		ZipUtil.unzip(iserverZip_local, iserverPath_local);
		//启动iserver
		String[] cmd = {"cmd", "/C", startBatPath};
		if (!new File(startBatPath).exists()) {
			throw new Exception(startBatPath + "不存在。");
		}
		try {
			Info.out("启动iserver...");
			Runtime.getRuntime().exec(cmd, null, new File(new File(startBatPath).getParent()));
			//等待iserver启动完成
			Condition cond = new Condition() {
				@Override
				public boolean test() {
					URL url;
					try {
						url = new URL("http://localhost:8090");
						url.openStream();
						Info.out("iserver 启动成功。");
						return true;
					} catch (Exception e1) {
						//继续等待启动
					}
					return false;
				}
			};
			try {
				abbot.tester.Robot.wait(cond, 90000);
			} catch (WaitTimedOutException wto) {
				throw new ActionFailedException("iserver 启动失败。");
			}

			//开始发布iserver服务
			//打开工作空间
			new CommonOperation().toFront();
			new CommonOperation().openSMWU(workspacePath);
			new WorkspaceTreeOperation().selectWorkspaceNodeMenu("发布工作空间...");
			DialogOperation dialogOperation = new DialogOperation(CrossProperties.getProperty(CrossProperties.PropertiesEnum.NetServices, "String_button_addFile"));
			//远程服务
			dialogOperation.clickComponent(new NameMatcher("JDialogServerRelease_radioButtonRemoteHost"));
			//参数设置，地图服务那些是默认勾选的
			dialogOperation.clickComponent(new NameMatcher(""));
			dialogOperation.setTextComponentValue(new NameMatcher("JDialogServerRelease_textFieldHost"), "http://localhost:8090");
			dialogOperation.setTextComponentValue(new NameMatcher("JDialogServerRelease_textFieldUserName"), "admin");
			dialogOperation.setTextComponentValue(new NameMatcher("JDialogServerRelease_textFieldPassword"), "Aa111111");
			dialogOperation.clickComponent(new NameMatcher("JDialogServerRelease_checkBoxWCS111"));
			dialogOperation.clickComponent(new NameMatcher("JDialogServerRelease_checkBoxWMS111"));
			dialogOperation.clickComponent(new NameMatcher("JDialogServerRelease_checkBoxWCS112"));
			dialogOperation.clickComponent(new NameMatcher("JDialogServerRelease_checkBoxWMS130"));
			dialogOperation.clickComponent(new NameMatcher("JDialogServerRelease_checkBoxWFS100"));
			dialogOperation.clickComponent(new NameMatcher("JDialogServerRelease_checkBoxWMTS100"));
			dialogOperation.clickComponent(new NameMatcher("JDialogServerRelease_checkBoxWPS100"));
			dialogOperation.clickComponent(new NameMatcher("JDialogServerRelease_checkBoxWMTSCHINA"));
			dialogOperation.clickComponent(new NameMatcher("JDialogServerRelease_checkBoxIsEditable"));
			dialogOperation.clickComponent(new NameMatcher("JDialogServerRelease_buttonRelease"));
			//确认选择，默认
			DialogOperation selectDialogOperation = new DialogOperation(CrossProperties.getProperty(CrossProperties.PropertiesEnum.NetServices, "String_Title_ConfirmSelection"));
			selectDialogOperation.clickComponent(new NameMatcher("JDialogFolderSelector_buttonOk"));
			robot.delay(2000);
			new CommonOperation().waitForProgressDispose(500000);

			//结果检查
			String[] resultIP = new String[]{
					"http://localhost:8090/iserver/services/map-China/rest/maps/China",
					"http://localhost:8090/iserver/services/map-China/wmts-china",
					"http://localhost:8090/iserver/services/map-China/wms111",
					"http://localhost:8090/iserver/services/map-China/wmts100",
					"http://localhost:8090/iserver/services/data-China/rest",
					"http://localhost:8090/iserver/services/spatialAnalysis-China/wps100",
					"http://localhost:8090/iserver/services/map-China/wms130",
					"http://localhost:8090/iserver/services/spatialAnalysis-China/restjsr",
					"http://localhost:8090/iserver/services/data-China/wcs111",
					"http://localhost:8090/iserver/services/data-China/wcs112",
					"http://localhost:8090/iserver/services/data-China/wfs100"
			};
			for (String ip : resultIP) {
				try {
					URL url = new URL(ip);
					url.openStream();
				} catch (Exception e1) {
					throw e1;
				}
			}
			//打开地图查看
			new WorkspaceTreeOperation().selectTheDatasouceNodeMenu("打开 Web 型数据源...");
			DialogOperation dialogOperationWebUDB = new DialogOperation();
			dialogOperationWebUDB.selectListItem(new NameMatcher("JDialogDatasourceOpenAndNew_listDatasourceType"), "iServerREST");
			dialogOperationWebUDB.setTextComponentValue(new NameMatcher("JPanelDatasourceInfoWeb_jTextFieldServerAddress"), resultIP[0]);
			dialogOperationWebUDB.clickComponent(new NameMatcher("JDialogDatasourceOpenAndNew_buttonOk"));
			new WorkspaceTreeOperation().selectDatasetNodeMenu("iServerREST", "China", "添加到新地图");
			new MapOperation().setCenter(new Point2D(12558297, 3748716.5), false);
			new MapOperation().setScale("1,155,583.419");

			new MapOperation().waitForDrawn(20000);
			new MapOperation().saveAsPicture(picturePath + "testIServer.png");
		} finally {
			new CommonOperation().toFront();
			//关闭服务
			String[] shutdownCmd = {"cmd", "/C", shutdownBatPath};
			if (!new File(startBatPath).exists()) {
				throw new Exception(startBatPath + "不存在。");
			}
			Runtime.getRuntime().exec(shutdownCmd, null, new File(new File(shutdownBatPath).getParent()));
			new CommonOperation().toFront();
		}
	}

}
